package com.amigo.online.provider.adv.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.param.common.KeyValueModel;
import com.amigo.online.provider.adv.common.ConstantValue;
import com.amigo.online.provider.adv.mapper.AdvHomeStockMapper;
import com.amigo.online.provider.adv.service.AdvHomeClickRecordService;
import com.amigo.online.provider.adv.service.AdvHomeLookRecordService;
import com.amigo.online.provider.adv.service.AdvHomeStockService;
import com.amigo.online.provider.adv.service.common.AbstractAdvStockService;

@Service
public class AdvHomeStockServiceImpl extends AbstractAdvStockService implements AdvHomeStockService {

    @Autowired
    AdvHomeStockMapper advHomeStockMapper;

    @Autowired
    AdvHomeLookRecordService advHomeLookRecordService;

    @Autowired
    AdvHomeClickRecordService advHomeClickRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void storageAdvRestNumberFromRedis(List<KeyValueModel<Long, Integer>> updateObjectList) {
        advHomeStockMapper.storageAdvRestNumberFromRedis(updateObjectList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordLookHomeAdv(Long advId, String device, Long userId) {
        //扣减库存
        long result = stockService.stock(ConstantValue.ADV_HOME_STOCK, String.valueOf(advId), -1);
        if (result == 0) {
            //该广告库存已经消耗完,   是否需要清空list？
            //手动入库
            advHomeStockMapper.recordOverUsedNumber(advId);
        } else if (result == -1) {
            logger.error("该首页资源未被正确初始化: 资源的ID:" + advId);
        }

        advHomeLookRecordService.recordHomeAdvLooked(advId, device, userId);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recordClickHomeAdv(Long advId, String device, Long userId) {
        advHomeStockMapper.recordClickNumber(advId);
        advHomeClickRecordService.recordHomeAdvClicked(advId, device, userId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void deductionHomeAdvLookStock(long advId) {
        //扣减库存
        long result = stockService.stock(ConstantValue.ADV_HOME_STOCK, String.valueOf(advId), -1);
        if (result == 0) {
            //该广告库存已经消耗完,   是否需要清空list？
            //手动入库
            advHomeStockMapper.recordOverUsedNumber(advId);
        } else if (result == -1) {
            logger.error("该首页资源未被正确初始化: 资源的ID:" + advId);
        }
    }

}
